package com.wonders.hisdoctor.station.project.medicine.controller;

import com.wonders.his.common.bean.BaseResult;
import com.wonders.his.common.exception.CustomException;
import com.wonders.his.common.service.project.base.domain.AppBaseParam;
import com.wonders.his.common.utils.StringUtils;
import com.wonders.his.framework.service.TokenService;
import com.wonders.hisdoctor.station.constant.Constants;
import com.wonders.hisdoctor.station.project.base.domain.OutpPresc;
import com.wonders.hisdoctor.station.project.hisqueue.vo.ClinicMasterQueryVo;
import com.wonders.hisdoctor.station.project.medicine.service.MedicineService;
import com.wonders.hisdoctor.station.project.medicine.vo.*;
import com.wonders.hisdoctor.station.project.record.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Description: 门诊用药
 *
 * @author tong-aj
 * <p>Create: 2021-01-18 16:49
 */
@Api(tags = "门诊用药")
@RestController
@RequestMapping("/medicine")
public class MedicineController {
    @Autowired
    private MedicineService medicineService;

    @Autowired
    private TokenService tokenService;

    /**
     * @param medicineVo 保存_VO
     * @return Integer
     */
    @ApiOperation("保存")
    @PostMapping("save")
    public BaseResult<Integer> save(@Valid @RequestBody MedicineVO medicineVo) {
        return BaseResult.success(medicineService.save(medicineVo));
    }

    @ApiOperation("查询_处方明细")
    @PostMapping("qryPres")
    public BaseResult<List<PrescriptionVO>> qryPres(@RequestBody QryPresVO qryPresVO) {
        final List<PrescriptionVO> prescriptionVOList = medicineService.qryPres(qryPresVO);
        StringBuilder msg = new StringBuilder();
        if (qryPresVO.getIsHistory() == null) {
            for (Iterator<PrescriptionVO> iterator = prescriptionVOList.iterator(); iterator.hasNext(); ) {
                final PrescriptionVO vo = iterator.next();
                if (vo.getSupplyIndicator() == 0) {
                    msg.append("[").append(vo.getDrugName()).append(" ").append(vo.getDrugSpec()).append("], ").append("已下柜, 请重新选药!<br/>");
                }
            }
        }
        return BaseResult.success(prescriptionVOList, msg.toString());
    }

    @ApiOperation("批量删除")
    @DeleteMapping("deleteBatch")
    public BaseResult<Integer> deleteBatch(@RequestBody List<OutpPresc> outpPrescs) {
        return BaseResult.success(medicineService.deleteBatch(outpPrescs));
    }

    @ApiOperation("查询_就诊记录")
    @PostMapping("qryClinic")
    public BaseResult<List<ClinicMasterQueryVo>> qryClinic(@RequestBody QryClinicVO qryClinicVO) {
        return BaseResult.success(medicineService.qryClinic(qryClinicVO));
    }


    /**
     * TODO 已废弃_待删
     * <p>
     * 查询 处方及明细
     *
     * @param patientId 病人ID
     * @param visitDate 就诊日期
     * @param visitNo   就诊序号
     * @return List<OutpOrders>
     */
    @ApiOperation("查询处方明细表")
    @GetMapping("queryPrescriptions")
    public BaseResult<List<PrescriptionVO>> queryPrescriptions(String patientId, @DateTimeFormat(pattern = "yyyy-MM-dd") Date visitDate, Integer visitNo, String empNo, Integer isHistory) {
        if (visitNo == null || StringUtils.isEmpty(patientId) || visitDate == null) {
            return BaseResult.fail("未传入病人信息!");
        }
        List<PrescriptionVO> prescriptionVos = medicineService.queryPrescriptions(patientId, visitDate, visitNo, empNo, isHistory);
        return BaseResult.success(prescriptionVos);
    }

    /**
     * 打印
     */
    @ApiOperation("打印处方")
    @PostMapping("/print")
    public BaseResult<PrintVo> print(@RequestBody MedicinePrintRequest medicinePrintRequest) {

        return BaseResult.success(medicineService.print(medicinePrintRequest));
    }

    @ApiOperation("查询医嘱明细下拉框")
    @PostMapping("/drugList")
    public BaseResult<DrugListVo> drugList(@RequestBody DrugListRequest drugListRequest) {
        List<DrugListVo> data = medicineService.drugList(drugListRequest);
        return BaseResult.success(data);
    }

    /**
     * 耗材_下拉框
     */
    @ApiOperation("耗材下拉")
    @GetMapping("supplies")
    public BaseResult<List<SuppliesVo>> supplies(String drugName, String hospitalCode, String type) {
        return BaseResult.success(medicineService.supplies(drugName, hospitalCode, type));
    }

    /**
     * 引用处方_左列表
     *
     * @param empNo     人员编号
     * @param patName   患者姓名
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return List<QuotePrescLeftVo>
     */
    @ApiOperation("引用处方_左列表")
    @GetMapping("quotePrescLeft")
    public BaseResult<List<QuotePrescLeftVo>> quotePrescLeft(String empNo, String patName,
                                                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                                             @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        List<QuotePrescLeftVo> quotePrescLeftVos = medicineService.quotePrescLeft(empNo, patName, startDate, endDate);
        return BaseResult.success(quotePrescLeftVos);
    }

    /**
     * 引用处方_右列表
     *
     * @param empNo     人员编号
     * @param patName   患者姓名
     * @param visitDate 就诊日期
     * @return List<OutpPresc>
     */
    @ApiOperation("引用处方_右列表")
    @GetMapping("quotePresc")
    public BaseResult<List<QuotePrescVo>> quotePrescription(String empNo, String patName,
                                                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date visitDate) {
        return BaseResult.success(medicineService.quotePrescription(empNo, patName, visitDate));
    }

    /**
     * 治疗单打印
     *
     * @param treatPrintVo 入参
     * @return DrugTreatPrintVo
     */
    @ApiOperation("治疗单_打印")
    @PostMapping("drugTreatPrint")
    public BaseResult<DrugTreatPrintVo> drugTreatPrint(@RequestBody TreatPrintVo treatPrintVo) {
        List<CompPkVo> compPkVos = treatPrintVo.getCompPkVos();
        for (CompPkVo compPkVo : compPkVos) {
            String serialNo = compPkVo.getSerialNo();
            if (StringUtils.isEmpty(serialNo)) {
                throw new CustomException("有未保存处方, 请先保存, 或重新选择!");
            }
        }
        final DrugTreatPrintVo printVo = medicineService.drugTreatPrint(treatPrintVo);
        final List<OutpPrescVo> outpPrescVos = printVo.getOutpPrescVos();
        // 下柜的药, 给以提示
        StringBuilder msg = new StringBuilder();
        for (OutpPrescVo outpPrescVo : outpPrescVos) {
            if (outpPrescVo.getSupplyIndicator() == 0) {
                msg.append("[").append(outpPrescVo.getDrugName()).append(" ").append(outpPrescVo.getDrugSpec()).append("], ").append("已下柜, 请重新选药并打印!<br/>");
            }
        }
        return BaseResult.success(printVo, msg.toString());
    }

    /**
     * 取消成组
     */
    @ApiOperation("取消成组")
    @PostMapping("ungroup")
    public BaseResult<Integer> ungroup(@RequestBody List<CompPkVo> compPkVos) {
        return BaseResult.success(medicineService.ungroup(compPkVos));
    }

    /**
     * 确认转方_校验
     */
    @ApiOperation("确认转方_校验")
    @PostMapping("checkPresc")
    public BaseResult<String> checkPresc(@RequestBody List<QuotePrescVo> quotePrescVos, String patientId) {
        return BaseResult.success(medicineService.checkPresc(quotePrescVos, patientId));
    }

    @ApiOperation("重复开药校验")
    @GetMapping("medicineRepeatable/{orgId}")
    public BaseResult<Integer> medicineRepeatable(@PathVariable("orgId") String orgId) {
        AppBaseParam appBaseParam = medicineService.medicineRepeatable(orgId);
        if (appBaseParam != null && appBaseParam.getValueName().equals(Constants.UN_VALIDATE)) {
            return BaseResult.success(Integer.valueOf(Constants.UN_VALIDATE), "可以重复开药");
        }
        return BaseResult.success(Integer.valueOf(Constants.VALIDATE), "不允许重复开药");
    }

    @ApiOperation("输液单打印")
    @PostMapping("getTransfusion")
    public BaseResult<TransfusionVo> getTransfusion(@RequestBody TransfusionRequest request) {
        return BaseResult.success(medicineService.getTransfusion(request));
    }

    @ApiOperation("用量配置")
    @GetMapping("dosageConfig")
    public BaseResult<DosageConfigVO> dosageConfig(String hospitalCode) {
        return BaseResult.success(medicineService.dosageConfig(hospitalCode));
    }

    @ApiOperation("根据剂型获取给药方式")
    @GetMapping("getAdminByForm")
    public BaseResult<Map<String, String>> getAdminByForm(String drugCode, String drugSpec) {
        return BaseResult.success(medicineService.getAdminByForm(drugCode, drugSpec));
    }
}
